from functools import wraps
from flask import request, jsonify, g

from app.utils.exceptions import MissingAuthorizationHeaderError, PermissionDeniedError
from app.auth import validate_access_token


def login_required(f):
    """登录状态验证装饰器"""

    @wraps(f)  # 保留被装饰函数的元数据
    def decorated_function(*args, **kwargs):
        # 检查access token
        auth_header = request.headers.get('Authorization')
        if not auth_header or not auth_header.startswith('Bearer '):
            raise MissingAuthorizationHeaderError({"o-facingMsg": "授权头失效"})
        token = auth_header.split(' ')[1].strip()
        if not token:
            raise MissingAuthorizationHeaderError({"o-facingMsg": "授权头失效"})

        # 验证Token有效性
        user_info = validate_access_token(token)
        if not user_info:
            raise MissingAuthorizationHeaderError({"o-facingMsg": "授权头失效"})
        g.user_role = user_info.get("user_role")
        g.user_id = user_info.get("user_id")
        print("test3".center(60, "="))
        print(user_info)
        print("test3".center(60, "="))
        print(g.__dict__)
        return f(*args, **kwargs)

    return decorated_function


def role_required(*allowed_roles):
    """角色权限验证装饰器"""

    def decorator(f):
        @wraps(f)
        def wrapper(*args, **kwargs):
            print(g.__dict__)
            valid_roles = list(allowed_roles)
            if "all_teacher" in valid_roles:
                valid_roles += ["teacher", "group_leader", "department_head", "admin", "dev_operator"]
            # 如果遇到 user_role 报错，请检查报错的接口是否使用了 login_required 装饰器，否则全局信息没有配置
            if g.user_role not in valid_roles:
                raise PermissionDeniedError(request.path, user_id=g.get("user_id"))
            return f(*args, **kwargs)

        return wrapper

    return decorator
